//
//  AddBowenViewController.m
//  YiqiMobile
//
//  Created by henry on 13-5-4.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "AddBowenViewController.h"
#import "Utility.h"
#import "Utility.h"
#import "Config.h"
#import "QuartzCore/QuartzCore.h"
#import "CustomNavigationController.h"
#import "AppDelegate.h"
#import "JSON.h"
#import "DefineAction.h"

@interface AddBowenViewController ()

@end

@implementation AddBowenViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.titleView=[Utility getTitleView:@"新建博文"];
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(backToPre) normalImage:@"navback_normal.png" lightedImage:@"navback_hover.png" frame:CGRectMake(0, 0, 58, 29) title:nil tag:10]];
    backBarButtonItem.style = UIBarButtonItemStylePlain;
    self.navigationItem.leftBarButtonItem = backBarButtonItem;
    
    UIImageView *backgroundimageView=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,200)];
    backgroundimageView.userInteractionEnabled=YES;
    UIImage *image=[Utility imageNamed:@"cg_bg2.png"];
    UIEdgeInsets insets=UIEdgeInsetsMake(10, 0, 50, 0);
    if ([[[UIDevice currentDevice] systemVersion] floatValue]<6.0) {
        image=[image resizableImageWithCapInsets:insets];
    }else{
        image=[image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    }
    backgroundimageView.image=image;
    [self.view addSubview:backgroundimageView];
    
    UIImageView *titleinputBg=[[UIImageView alloc] initWithFrame:CGRectMake(8, 10, 304, 44)];
    titleinputBg.userInteractionEnabled=YES;
    titleinputBg.image=[Utility imageNamed:@"biaoti_title.png"];
    [self.view addSubview:titleinputBg];
    self.titleField = [self customTextField:CGRectMake(8, 3, 288, 37)];
    self.titleField.placeholder=@"输入博文标题";
    self.titleField.delegate=self;
    [titleinputBg
     addSubview:self.titleField];
    
    
    UIImageView *contentFieldbg=[[UIImageView alloc] initWithFrame: CGRectMake(8, 58, 304, 97)];
    contentFieldbg.userInteractionEnabled=YES;
    contentFieldbg.image=[Utility imageNamed:@"biaoti_content.png"];
    [self.view addSubview:contentFieldbg];
    
    
    self.contentField=[[UITextView alloc] initWithFrame:CGRectMake(2, 0, 300, 90)];
    self.contentField.text=@"简介";
    self.contentField.backgroundColor=[UIColor  clearColor];
    //self.contentField.layer.cornerRadius = 8;//设置那个圆角的有多圆
    self.contentField.layer.borderWidth = 0;//设置边框的宽度，当然可以不要
    //self.contentField.layer.borderColor = [[UIColor blackColor] CGColor];//设置边框的颜色
    self.contentField.keyboardType=UIKeyboardTypeDefault;
    self.contentField.layer.masksToBounds = YES;//设为NO去试试
    self.contentField.autocorrectionType=UITextAutocorrectionTypeNo;
    self.contentField.returnKeyType=UIReturnKeyDone;
    self.contentField.textColor=[UIColor lightGrayColor];
    self.contentField.font=[UIFont fontWithName:FONT_FAMILY size:15.0];
    self.contentField.enablesReturnKeyAutomatically=YES;
    self.contentField.delegate=self;
    [contentFieldbg addSubview:self.contentField];

    
    //显示隐藏供稿菜单
    [self.view addSubview:[Utility customButton:self action:@selector(popmenuAction:) normalImage:@"biaoti_addgongao.png" lightedImage:@"biaoti_addgongao.png" frame:CGRectMake(45,208,260,100) title:nil tag:0]];
    
    //显示隐藏博文简介
    [self.view addSubview:[Utility customButton:self action:@selector(showorhideAction:) normalImage:@"biaoti_showcontent.png" lightedImage:@"biaoti_showcontent.png" frame:CGRectMake(230, 158, 75, 22) title:nil tag:0]];
    
    //弹出菜单
    [self initPopMenu];
    //初始化语音
    self.voiceRecord=[[VoiceRecord alloc] init];
    
	// Do any additional setup after loading the view.
}

-(void) backToPre{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"请保存博文标题" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存", nil];
    [alert show];

}

#pragma marks -- UIAlertViewDelegate --
//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 1:{
            if (self.titleField.text.length<1) {
                [alertView dismissWithClickedButtonIndex:1 animated:YES];
                [Utility customAlertWithMsg:@"请输入博文标题" andTitle:@"提醒" andDelagate:nil];
            }else{
                [self savebowenwithType:1 andContent:@""];
            }
            break;
        }
        default:{
            [self.navigationController  popViewControllerAnimated:YES];
            break;
        }
    }
}
//保存博文
-(void) savebowenwithType:(int) type andContent:(NSString*)ggcontent{
    NSString *title=self.titleField.text;
     NSString *content=self.contentField.text;
    NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    if (title==nil||[title isEqualToString:@""]) {
        [Utility customAlertWithMsg:@"请输入博文标题" andTitle:ALRRTTITLE andDelagate:nil];
        return;
	}
    NSString *url=[NSString stringWithFormat:@"%@/%@?type=0",[Utility  getServerUrl],CREATEBIAOTIACTION];
    NSMutableDictionary *param=[NSMutableDictionary dictionary];
    param[@"b.b1"]=title;//博文标题
    param[@"b.u0"]=userId;//标题创建人
    param[@"b.e0"]=self.quanziId;//所属圈子
    param[@"b.b4"]=content;//简介
    param[@"b.b6"]=@"";//标签
    param[@"b.wt0"]=@"1";//所属网站分类
    if (ggcontent.length>0) {//是否同时新增一个供稿 0 是(那么下面参数需要)  1否
        param[@"type"]=@"0";//是否同时新增一个供稿 0 是(那么下面参数需要)  1否
        param[@"g.t0"]=@(type);//供稿内容类型
        param[@"g.g2"]=ggcontent;//供稿内容（文字）
    }else{
          param[@"type"]=@"1";
    }
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
    [self.request startLoadData];
}
- (void)requestFinished:(id)context{
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result objectForKey:@"code"] integerValue]==0) {
            
            if ([[result objectForKey:@"method"] isEqualToString:CREATEBIAOTIACTION]) {
                NSLog(@"%@",@"createB");
                UIViewController *viewController=[[self.navigationController viewControllers] objectAtIndex:0];
                if ([viewController respondsToSelector:@selector(loadDataFromServer)]) {
                    [viewController performSelector:@selector(loadDataFromServer) withObject:nil];
                    [self.navigationController  popToViewController:viewController animated:YES];
                }
                
            }
            
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}


-(void) showorhideAction:(UIButton*) sender{
    NSLog(@"%@",@"显示或者隐藏简介");
}

//供稿菜单
-(void) popmenuAction:(UIButton*) sender{
    if (self.titleField.text.length<1) {
        [Utility customAlertWithMsg:@"请输入博文标题" andTitle:@"提醒" andDelagate:nil];
        return;
    }
    UIView *popView=[self.view viewWithTag:POPMENUTAG];
    popView.hidden=!popView.hidden;
}

-(void) onclickMenuAction:(UIButton*) sender{
    switch (sender.tag) {
        case POPBUTTONTAG+1:{
            AddGonggaoViewController *add=[[AddGonggaoViewController alloc] initWithNibName:nil bundle:nil];
            add.delegate=self;
            [add topRow];
            CustomNavigationController *nav=[[CustomNavigationController alloc] initWithRootViewController:add];
            [self presentViewController:nav animated:YES completion:nil];
            break;
        }
        case POPBUTTONTAG+2:{
            self.takephoto=[[TakePhoto alloc] init];
            [_takephoto setupCamera:self];
            break;
        }
        case POPBUTTONTAG+3:{
            self.takephoto=[[TakePhoto alloc] init];
            [_takephoto setupLibrary:self];
            break;
        }
        case POPBUTTONTAG+4:{
            
            break;
        }
            
    }
    
    
}

#pragma -mark camera delegate
-(void) didTakePicture:(NSData *) rawImage{
    NSLog(@"拍照成功");
}

#pragma -mark AddGonggaoViewControllerDelegate
-(void) success:(NSDictionary*)param{
    UIView *popView=[self.view viewWithTag:POPMENUTAG];
    popView.hidden=YES;
    [self dismissViewControllerAnimated:YES completion:nil];
    [self savebowenwithType:1 andContent:[param objectForKey:@"ggContent"]];
}


//语音
-(void)longPressBtn:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state]==UIGestureRecognizerStateBegan){//长按事件开始
        UIView *viewDailag=[self.view viewWithTag:90001];
        viewDailag.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"dialogButton_pressed.png"]];
        NSLog(@"开始");
        [self.voiceRecord recordBtnClick:@"0"];
        
        
    }else if([gestureRecognizer state]==UIGestureRecognizerStateEnded){//长按事件
        UIView *viewDailag=[self.view viewWithTag:90001];
        viewDailag.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"dialogButton.png"]];
        [self.voiceRecord recordBtnClick:@"0"];
        NSLog(@"结束");
    }
}


- (BOOL) textViewShouldBeginEditing:(UITextView *)textView{
    self.contentField.textColor=[UIColor blackColor];
    self.contentField.text = @"";
    return YES;
}
-(void) textViewDidChange:(UITextView *)textView{
    if(self.contentField.text.length == 0){
        self.contentField.textColor = [UIColor lightGrayColor];
        self.contentField.text = @"简介";
        [self.contentField resignFirstResponder];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    if ([text isEqualToString:@"\n"]) {//按下return键
        [self.contentField resignFirstResponder];
        return NO;
    }else {
        if ([textView.text length] < 140) {//判断字符个数
            return YES;
        }
    }
    return NO;
}

#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==self.titleField) {
        if (self.titleField.text.length>0) {
            [self.contentField becomeFirstResponder];
            return YES;
        }
    }
    return NO;
}



-(void) initPopMenu{
    
    UIView *popView =[[UIView alloc] initWithFrame:CGRectMake(0,215, 260, 43)];
    popView.backgroundColor=[UIColor clearColor];
    popView.tag=POPMENUTAG;
    popView.hidden=YES;
    UIButton *button1=[Utility customButton:self action:@selector(onclickMenuAction:) normalImage:@"cg_write_normal.png" lightedImage:@"cg_write_hover.png" frame:CGRectMake(13, 0, 43, 43) title:nil tag:POPBUTTONTAG+1];
    [popView addSubview:button1];
    
    UIButton *button2=[Utility customButton:self action:@selector(onclickMenuAction:) normalImage:@"cg_camera_normal.png" lightedImage:@"cg_camera_hover.png" frame:CGRectMake(72, 0, 43, 43) title:nil tag:POPBUTTONTAG+2];
    [popView addSubview:button2];
    UIButton *button3=[Utility customButton:self action:@selector(onclickMenuAction:) normalImage:@"cg_photo_normal.png" lightedImage:@"cg_photo_hover.png" frame:CGRectMake(130, 0, 43, 43) title:nil tag:POPBUTTONTAG+3];
    [popView addSubview:button3];
    
    UIButton *button4=[Utility customButton:self action:@selector(onclickMenuAction:) normalImage:@"cg_voice_normal.png" lightedImage:@"cg_voice_hover.png" frame:CGRectMake(190, 0, 43, 43) title:nil tag:POPBUTTONTAG+4];
    [popView addSubview:button4];
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressBtn:)];
    [longPressGesture setDelegate:self];
    longPressGesture.minimumPressDuration=0.3;//默认0.5秒
    [button4 addGestureRecognizer:longPressGesture];
    [self.view addSubview:popView];
}




-(UITextField*) customTextField:(CGRect) frame{
    
    UITextField *textFied = [[UITextField alloc] initWithFrame:frame];
    textFied.keyboardType=UIKeyboardAppearanceDefault;
    textFied.autocorrectionType = UITextAutocorrectionTypeNo;
    textFied.returnKeyType=UIReturnKeyNext;
    textFied.clearButtonMode=UITextFieldViewModeWhileEditing;
    textFied.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    textFied.backgroundColor=[UIColor  clearColor];
    textFied.borderStyle=UITextBorderStyleNone;
    textFied.textColor=[UIColor blackColor];
    textFied.font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
    textFied.autocorrectionType=UITextAutocorrectionTypeNo;
    [textFied setBorderStyle:UITextBorderStyleNone];
    textFied.returnKeyType = UIReturnKeyDone;
    textFied.keyboardType=UIKeyboardTypeDefault;
    return textFied;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
